<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <title>围棋练习</title>
    <link rel="stylesheet" type="text/css" href="css/go.css">
    <script src="js/event.js"></script>
    <script src="js/file.js"></script>
    <script src="js/go.js"></script>
    <script type="text/javascript" src="js/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/layer/2.4/layer.js"></script>
    <script type="text/javascript" src="js/bootstrap/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="js/bootstrap/css/bootstrap.min.css" />

</head>

<body>
    <div id="container">
        <article style="float: left;margin-right: 50px;">
            <section>
                <svg id="chessboard" width="600" height="600" style="background: GoldenRod">
                    <defs>
                        <radialGradient id="rgBlack" cx="25%" cy="25%" r="50%" fx="25%" fy="25%">
                            <stop offset="0%" style="stop-color:rgb(200,200,200);stop-opacity:1" />
                            <stop offset="100%" style="stop-color:rgb(0,0,0);stop-opacity:1" />
                        </radialGradient>
                        <radialGradient id="rgWhite" cx="25%" cy="25%" r="50%" fx="25%" fy="25%">
                            <stop offset="0%" style="stop-color:rgb(255,255,255);stop-opacity:1" />
                            <stop offset="100%" style="stop-color:rgb(200,200,200);stop-opacity:1" />
                        </radialGradient>
                    </defs>
                </svg>
            </section>
        </article>
        <aside>
            <!-- <h3>模式选择</h3> -->
            <section style="display: none">
                <input type="radio" name="mode" value="auto" checked="checked">自动模式</input><br />
                <input type="radio" name="mode" value="manual">手动模式</input><br />
                <input type="button" id="changeMode" value="切换模式" />
            </section>

            <!--<h3>棋子选择</h3>-->
            <section>
                <p class="text-warning mt-30" style="font-size: 16px; font-weight: 500">棋子选择</p>
                <div class="radio">
                    <label>
                        <input type="radio" name="chess" value="black" checked="checked">执黑棋子</input>
                    </label>
                </div>
                <div class="radio">
                    <label>
                        <input type="radio" name="chess" value="white">执白棋子</input>
                    </label>
                </div>
                <input type="button" class="btn btn-warning" id="changeChess" value="切换棋子" />
            </section>
            <!-- <h3>其它按钮</h3> -->
            <section style="display: none">
                <input type="button" id="goback" value="后退一步" /><br />
                <input type="button" id="goforward" value="前进一步" /><br />
                <input type="button" id="clearChess" value="清空棋子" /><br />
                <input type="button" id="saveChess" value="保存棋局" /><br />
                <input type="button" id="loadChess" value="载入棋局" /><br />
                <input type="file" id="browse" width="0" height="0" style="opacity: 0" />
            </section>
            <input type="file" id="loadfile" width="0" height="0" style="opacity: 0;display:none" />
        </aside>
    </div>

    <script>
        var xmlns = 'http://www.w3.org/2000/svg',
            xlink = 'http://www.w3.org/1999/xlink';

        //第一次加载初始棋谱不进行校验判别
        var isFinishInit = false;
        //本节练习设定的步数
        var settingCount = 1;
        //从加载设定的棋谱后，开始计算本节练习步数
        var finsihCount = 0;

        //棋谱初始数据和每一步执行后的数据，可在服务器端获取
        var baseChess = "";
        var answerChess = "";

        //答案棋谱构成数组
        var answerChessArr = [];

        window.onload = function() {
            var chessmen = [],
                backs = [],
                forwards = [],
                index = 0,
                lineCount = 19, //此处可调节棋盘 19*19或者8*8;
                chessboard = document.getElementById('chessboard'),
                length = chessboard.getAttributeNS(null, 'width'),
                centerStar = Math.floor(lineCount / 2),
                leftStar = 3,
                rightStar = lineCount - 4,
                span = length / (lineCount + 1),
                pieceR = span * 0.45,
                starR = span * 0.1,
                hx1 = span,
                hy1 = span,
                hx2 = length - span,
                hy2 = span,
                vx1 = span,
                vy1 = span,
                vx2 = span,
                vy2 = length - span;
            for (var i = 0; i < lineCount; i++) {
                drawLine(chessboard, hx1, hy1, hx2, hy2);
                drawLine(chessboard, vx1, vy1, vx2, vy2);
                hy1 = hy2 += span;
                vx1 = vx2 += span;
            }
            for (var i = 0, hx1 = hy1 = span; i < lineCount; i++) {
                for (var j = 0, x = hx1; j < lineCount; j++) {
                    if ((i == leftStar || i == centerStar || i == rightStar) &&
                        (j == leftStar || j == centerStar || j == rightStar)) {
                        drawStar(chessboard, x, hy1, starR);
                    }
                    drawPiece(chessboard, x, hy1, pieceR);
                    x += span;
                }
                hy1 += span;
            }


            function drawLine(parent, x1, y1, x2, y2) {
                var line = document.createElementNS(xmlns, 'line');
                line.setAttribute('x1', x1 - 0.5);
                line.setAttribute('y1', y1 - 0.5);
                line.setAttribute('x2', x2 - 0.5);
                line.setAttribute('y2', y2 - 0.5);
                line.setAttribute('stroke', 'black');
                parent.appendChild(line);
            }

            function drawStar(parent, x, y, r) {
                var circle = document.createElementNS(xmlns, 'circle');
                circle.setAttribute('cx', x - 0.5);
                circle.setAttribute('cy', y - 0.5);
                circle.setAttribute('r', r);
                circle.setAttribute('fill', 'black');
                parent.appendChild(circle);
            }

            // 绘制 下棋的操作
            function drawPiece(parent, x, y, r) {

                var circle = document.createElementNS(xmlns, 'circle');
                circle.setAttribute('cx', x - 0.5);
                circle.setAttribute('cy', y - 0.5);
                circle.setAttribute('r', r);
                circle.index = index++;
                circle.status = function(status) {
                    var chess = this;
                    return status != null ? (function() {

                        //单节练习设定的总的操作数
                        if (finsihCount >= settingCount) {
                            layer.open({
                                title: "温馨提示 :",
                                content: "你已经完成本小节的练习 :)",
                                time: 1200
                            });
                            return;
                        }

                        switch (status) {
                            case '1':
                                chess.s = '1';
                                chess.setAttribute('fill', 'url(#rgBlack)');
                                chess.setAttribute('opacity', 1);
                                if (isFinishInit) {
                                    var flag = checkOutChess();
                                    if (flag) {
                                        chess.s = '0';
                                        chess.setAttribute('opacity', 0);
                                        layer.open({
                                            title: "错误提示 :",
                                            content: "黑旗位置错误 :(",
                                            time: 2000
                                        });
                                        return;
                                    }
                                }
                                break;
                            case '2':
                                chess.s = '2';
                                chess.setAttribute('fill', 'url(#rgWhite)');
                                chess.setAttribute('opacity', 1);
                                if (isFinishInit) {
                                    var flag = checkOutChess();
                                    if (flag) {
                                        chess.s = '0';
                                        chess.setAttribute('opacity', 0);
                                        layer.open({
                                            title: "错误提示 :",
                                            content: "白旗位置错误 :(",
                                            time: 2000
                                        });
                                        return;
                                    }
                                }
                                break;
                            default:
                                chess.s = '0';
                                chess.setAttribute('opacity', 0);
                                break;
                        }
                        return this.s;
                    })() : this.s;
                }
                circle.status('0');
                eventHelper.addEvent(circle, 'click', function() {
                    var chess = getRadioValueByName('chess'),
                        piece = chess == 'black' ? '1' : '2',
                        tmp = [getStatus(this)],
                        pieces = [];
                    if (this.status() == '0') {
                        if (goHelper.hasDeadPieces(this.index, piece == '1' ? '2' : '1', getAllStatus(
                                this.index,
                                piece))) {
                            pieces = goHelper.getDeadPieces();
                            for (var i = 0, tmppiece; i < pieces.length; i++) {
                                tmppiece = chessmen[pieces[i]];
                                tmp.push(getStatus(tmppiece));
                                tmppiece.status('0');
                            }
                        } else if (!goHelper.hasWay(this.index, piece, getAllStatus(this.index, piece),
                                pieces)) {
                            return;
                        }
                        this.status(piece);
                        if (getRadioValueByName('mode') == 'auto') {
                            checkRadioByName('chess', chess == 'black' ? 'white' : 'black');
                        }
                    } else {
                        this.status('0');
                    }
                    backs.push(tmp);
                    forwards = [];
                });
                parent.appendChild(circle);
                chessmen.push(circle);
            }

            //模式选择
            eventHelper.addEvent(document.getElementById('changeMode'), 'click', function() {
                checkRadioByName('mode', getRadioValueByName('mode') == 'auto' ? 'manual' : 'auto');
            });
            //棋子选择
            eventHelper.addEvent(document.getElementById('changeChess'), 'click', function() {
                checkRadioByName('chess', getRadioValueByName('chess') == 'black' ? 'white' : 'black');
            });

            //后退一步
            eventHelper.addEvent(document.getElementById('goback'), 'click', function() {
                if (backs.length > 0) {
                    var last = backs.pop(),
                        tmp = [];
                    for (var i = 0; i < last.length; i++) {
                        tmp.push(getStatus(last[i].piece));
                        last[i].piece.status(last[i].status);
                    }
                    forwards.push(tmp);
                }
            });

            //前进一步
            eventHelper.addEvent(document.getElementById('goforward'), 'click', function() {
                if (forwards.length > 0) {
                    var last = forwards.pop(),
                        tmp = [];
                    for (var i = 0; i < last.length; i++) {
                        tmp.push(getStatus(last[i].piece));
                        last[i].piece.status(last[i].status);
                    }
                    backs.push(tmp);
                }
            });

            //清空棋子
            eventHelper.addEvent(document.getElementById('clearChess'), 'click', function() {
                var piece, tmp = [];
                for (var i = 0; i < chessmen.length; i++) {
                    piece = chessmen[i];
                    if (piece.status() == '0') continue;
                    tmp.push(getStatus(piece));
                    piece.status('0');
                }
                if (tmp.length > 0) {
                    backs.push(tmp);
                    forwards = [];
                }
            });

            //保存棋局
            eventHelper.addEvent(document.getElementById('saveChess'), 'click', function() {
                var file = prompt('请输入文件名称');
                if (file != null) {
                    if (file == '') {
                        alert('文件名不能为空');
                    } else {
                        fileHelper.download(file, getAllStatus().join(''));
                    }
                }
            });

            //载入棋局
            eventHelper.addEvent(document.getElementById('loadChess'), 'click', function() {
                document.getElementById("browse").click();
            });

            eventHelper.addEvent(document.getElementById('browse'), 'change', function() {
                var file = document.getElementById("browse").files[0];
                fileHelper.upload(file, function(text) {
                    var piece, tmp = [];
                    for (var i = 0, maxChess = Math.pow(lineCount, 2); i < text.length && i <
                        maxChess; i++) {
                        piece = chessmen[i];
                        tmp.push(getStatus(piece));
                        piece.status(text[i]);
                    }
                    if (tmp.length > 0) {
                        backs.push(tmp);
                        forwards = [];
                    }
                });
            });

            function getStatus(piece) {
                return {
                    'piece': piece,
                    'status': piece.status()
                };
            }

            function getAllStatus(pos, status) {
                var all = [];
                for (var i = 0; i < chessmen.length; i++) {
                    all.push(i == pos ? status : chessmen[i].status());
                }
                return all;
            }

            function getRadioValueByName(name) {
                var radios = document.getElementsByName(name);
                for (var i = 0; i < radios.length; i++) {
                    if (radios[i].checked) return radios[i].value;
                }
                radios[0].checked = true;
                return radios[0].value;
            }

            function checkRadioByName(name, value) {
                var radios = document.getElementsByName(name);
                for (var i = 0; i < radios.length; i++) {
                    if (radios[i].value == value) {
                        radios[i].checked = true;
                        break;
                    }
                }
            }


            //Mine 写的方法

            //1.初始化页面首先加载棋局
            (function loadTheChess() {

                var baseUrl = "http://localhost/index/course/fetchCourseData";
                var paramStr = location.search;
                var courseId = paramStr.replace(/[^0-9]/ig, "");
                $.ajax({
                    type: "POST",
                    url: baseUrl,
                    data: {
                        id: courseId
                    },
                    dataType: "json",
                    success: function(res) {
                        if (res.status === 200) {
                            var course = res.data;
                            baseChess = course.base_chess;
                            initChessBoard(baseChess);
                            // console.log(baseChess);
                            answerChess = course.answer_chess;
                            console.log(answerChess);
                            settingCount = course.chess_step;
                            answerChessArr = answerChess.split(';');
                        } else {
                            alert("该练习课程不存在");
                        }
                    }
                });

            })();

            function initChessBoard(baseChess) {
                var text = baseChess;
                var piece, tmp = [];
                for (var i = 0, maxChess = Math.pow(lineCount, 2); i < text.length && i < maxChess; i++) {
                    piece = chessmen[i];
                    tmp.push(getStatus(piece));
                    piece.status(text[i]);
                }
                if (tmp.length > 0) {
                    backs.push(tmp);
                    forwards = [];
                }

                isFinishInit = true;
            }

            //2.学生每下一步棋 进行错误校验
            function checkOutChess() {


                //获取最新的棋谱
                var currentChessManual = getAllStatus().join('');
                var isCorrect = (answerChessArr[finsihCount] !== currentChessManual);


                //单步完成判定
                if (!isCorrect) {
                    finsihCount++;
                    if (finsihCount === settingCount) {
                        layer.open({
                            title: "温馨提示 :",
                            content: "你已经完成本小节的练习 :)",
                            time: 1200
                        });
                        return;
                    }

                    layer.open({
                        title: "温馨提示:",
                        content: "接着进行下一步",
                        time: 2000
                    });
                }

                return isCorrect;
            }
        }
    </script>

</body>

</html>